package com.sixth.service.Impl;

import com.sixth.dao.MenuDao;
import com.sixth.entity.Menu;
import com.sixth.entity.Staff;
import com.sixth.service.MenuService;
import com.sixth.util.CommonResult;
import com.sixth.util.WebUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @program: gp
 * @description:
 * @author: 老魏
 * @create: 2021-12-17 20:42
 **/
@Service(value = "menuservice")
public class MenuServiceImpl implements MenuService {

    @Autowired
    private MenuDao menuDao;

    public CommonResult findByUserRid() {
        Staff staff = (Staff) WebUtil.getSession().getAttribute("staff");
        List<Menu> list = menuDao.findMenuByUid(staff.getRoleid());

        List<Menu> first=new ArrayList<Menu>();//声明一个集合存放一级菜单
        //找到一级菜单
        for (Menu menu:list){
            if(menu.getMpid()==0){
                first.add(menu);
            }
        }
        //找到对应一级菜单下的二级菜单
        for (Menu f:first){
            List<Menu> children=new ArrayList<Menu>();//当前一级菜单的子菜单
            for(Menu menu:list){
                if(menu.getMpid().equals(f.getMid())){
                    children.add(menu);
                }
            }
            f.setChildren(children);
        }
        return new CommonResult(2000,"查询左侧菜单成功",first);
    }

    public CommonResult findAllMenu() {
        List<Menu> list = menuDao.selectAllMenu();
        List<Menu> first=new ArrayList<Menu>();//声明一个集合存放一级菜单

        //找到一级菜单
        for (Menu menu:list){
            if(menu.getMpid()==0){
                first.add(menu);
            }
        }

        //找到对应一级菜单下的二级菜单
        for (Menu f:first){
            List<Menu> children=new ArrayList<Menu>();//当前一级菜单的子菜单
            for(Menu menu:list){
                if(menu.getMpid().equals(f.getMid())){
                    children.add(menu);
                }
            }
            f.setChildren(children);
        }
        return new CommonResult(2000,"查询所有菜单成功",first);
    }

    //获取默认被选中的菜单
    public CommonResult findRoleMenuId(Integer roleid) {
        List<Integer> menuById = menuDao.findRoleMenuId(roleid);
        return new CommonResult(2000,"查询成功",menuById);
    }

    //修改权限
    @Override
    public CommonResult confirmPermission(Integer roleid, String[] mids) {
        menuDao.deleteRoleMenu(roleid);
        Integer i = menuDao.insertPermission(roleid, mids);
        if (i > 0) {
            return CommonResult.success(null,"修改成功");
        }
        return CommonResult.fail("修改失败");
    }
}
